package com.token.sysflow.core;
import com.token.sql.IntegrateSql;
import com.token.sysflow.enumerate.ApprovalTypeEnum;
import com.token.sysflow.exception.ErrorCodeEnum;
import com.token.sysflow.exception.FlowException;
import com.token.sysflow.hander.ApproveProcess;
import com.token.sysflow.impl.AbstractFlowHandlerImpl;
import com.token.sysflow.impl.CreateCallHQImpl;

/**
 * 发起组织会签
 * @author chenjianxiong 2020/4/13
 */
public class CallHQ extends AbstractFlowCore{
    public CallHQ(IntegrateSql f, String keyUnid) throws Exception{
        super(f,keyUnid);
    }

    @Override
    public void execute(AbstractFlowHandlerImpl flowHandler) throws Exception{
        CreateCallHQImpl callHQ  = (CreateCallHQImpl) flowHandler;

        //检查流程状态，结束和终止不允许操作
        checkFlowStatus();

        //只允许审批类型发起组织会签
        if(approveProcess.getApprovalType() != ApprovalTypeEnum.SP.getId()){
            throw new FlowException(ErrorCodeEnum.APPROVETYPE_CALLHQ);
        }

        //初始化起草人、申请人、当前人。
        initUserInfo(null,null,flowHandler.getActionUser());

        //判断当前用户是否是当前办理人
        if (!approveProcess.isStepApproves(callHQ.getActionUser(), ApproveProcess.STATUS_IND)) {
            throw new FlowException(ErrorCodeEnum.CHECK_APPROVE);
        }


        //判断开关，是否发起组织会签
        if(!getFromStep().isCanCame()){
            throw new FlowException(ErrorCodeEnum.CONFIG_HQ);
        }

        //设置目标流程
        super.setToFlow(fromFlow);

        //设置目标环节
        super.setToStep(fromStep);

        //当前办理人暂时保留
        approveProcess.updateApproverToPause(fromStep,flowHandler.getActionUser(),flowHandler.getOpinions());

        //必须在updateApproverToPause后面
        approveProcess.delStepApproving(fromStep);

        //更新审批数据
        super.updateApproveProcess(callHQ, ApprovalTypeEnum.ZZHQ);

        //写入新的办理人
        approveProcess.addToStepApprover(callHQ.getSelectApprover());

        //添加输出参数
        approveProcess.appendFlowProcessInfo(toFlow,toStep);

        //生成新的流转记录和办理意见
        super.createFlowApproveLog(callHQ);
    }

}
